import { genGood, genAllGood, genGoodTotal } from './good';

export function getGoodsList(baseID = 0, length = 10) {
  let list = new Array(length).fill(0).map((_, idx) => genGood(idx + baseID));
  return list;
}

export const goodsList = getGoodsList();

export const goodsListByParam = getGoodsListByParam();

export function getGoodsListByParam(param) {
  if (!param) param = {};
  const { pageSize, pageNum, minPrice, maxPrice, keyword, sort, sortType } = param;
  let list = genAllGood();
  if (minPrice && minPrice > 0) {
    list = list.filter(item => item.minSalePrice >= minPrice);
  }
  if (maxPrice && maxPrice > 0) {
    list = list.filter(item => item.minSalePrice <= maxPrice);
  }
  if (keyword) {
    list = list.filter(item => item.title.includes(keyword));
  }
  if (sort == 1) {
    if (sortType == 1) {
      list = list.sort((a, b) => b.minSalePrice - a.minSalePrice)
    } else if (sortType == 0) {
      list = list.sort((a, b) => a.minSalePrice - b.minSalePrice)
    }
  }
  const total = list.length;
  const { page, size, start, length } = getPageHelper(pageNum, pageSize, total);
  list = list.slice(start, start + length);
  return {
    pageNum: page,
    pageSize: size,
    total,
    list
  }
}

function getPageHelper(page = 1, size = 10, total = 0) {
  if (page <= 0) page = 1;
  const start = (page - 1) * size;
  const length = start + size > total ? (total - start) : size;
  return { page, size, start, length }
}

export function getGoodsPageList(pageNum = 0, pageSize = 10) {
  const total = genGoodTotal();
  const { page, start, length } = getPageHelper(pageNum, pageSize, total);
  let list = new Array(length).fill(0).map((_, idx) => genGood(idx + start));
  list = list.map((item) => {
    return {
      spuId: item.spuId,
      thumb: item.primaryImage,
      title: item.title,
      price: item.minSalePrice,
      originPrice: item.maxLinePrice,
      tags: item.spuTagList.map((tag) => tag.title),
    };
  })
  return {
    page,
    size: pageSize,
    total,
    list
  }
}
export const goodsPageList = getGoodsPageList();